
from rest_framework.generics import ListAPIView, RetrieveAPIView
from rest_framework import serializers
from meiduo_admin.my_paginate import MyPageNumberPagination
from orders.models import OrderInfo
from meiduo_admin.order import order_serializers
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import action


#1,order 管理
class OrderInfoView(ListAPIView):
    pagination_class = MyPageNumberPagination
    serializer_class = order_serializers.OrderInfoSerializer
    # queryset = OrderInfo.objects.order_by("order_id").all()

    # 1.重写数据源方法过滤订单
    def get_queryset(self):
        # 1.获取关键关键字
        keyword = self.request.query_params.get("keyword",'')

        # 2.返回数据源
        # if keyword:
        #     return OrderInfo.objects.filter(order_id__contains=keyword).order_by("order_id").all()
        # else:
        #     return OrderInfo.objects.order_by("order_id").all()

        return OrderInfo.objects.filter(order_id__contains=keyword).order_by("order_id").all()


#2,order detail 信息
class OrderInfoDetailView(RetrieveAPIView):
    serializer_class = order_serializers.OrderInfoDetailSerializer
    queryset = OrderInfo.objects.all()

# 3.使用视图集的形式，完成order；order detail 信息
class OrderInfoReadOnlymodelViewSet(ReadOnlyModelViewSet):
    pagination_class = MyPageNumberPagination

    #1,重写获取序列化器方法R
    def get_serializer_class(self):
        if self.action == 'list':

            return  order_serializers.OrderInfoSerializer
        else:
            return order_serializers.OrderInfoDetailSerializer


    # 2.重写获取数据集的方法
    def get_queryset(self):
        if self.action == 'list':
            keyword=self.request.query_params.get('keyword','')

            return OrderInfo.objects.filter(order_id__contains=keyword).order_by('order_id').all()


    # 3。修改订单状态
    @action (methods=["PUT"], detail=True)  # 路由格式, orders/{pk}/status
    def status(self,request,*args,**kwargs):
        pass
        # # 1,获取参数
        # stat = request.data.get(
        #     'status'
        # )
        # order = self.get_object()
        #
        # # 2.校验参数
        # if not stat:
        #     return Response(status=status.HTTP_400_BAD_REQUEST)
        #
        # # 3.数据入库
        # order.status = stat
        # order.save()
        #
        # # 4.返回响应
        # return Response(status=status.HTTP_200_OK)